package elastic.learn.transport.index.onedocument.curd;

import elastic.learn.transport.ElasticsearchConfig;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;
import java.util.concurrent.ExecutionException;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;

public class Update {
    public static void main(String[] args) throws ExecutionException, InterruptedException, IOException {
        TransportClient client = ElasticsearchConfig.getElasticsearchClient();
//        UpdateRequest updateRequest = new UpdateRequest();
//        updateRequest.index("twitter");
//        updateRequest.type("tweet");
//        updateRequest.id("1");
//        updateRequest.doc(jsonBuilder()
//                .startObject()
//                .field("user", "aaaa")
//                .endObject());
//        UpdateResponse response = client.update(updateRequest).get();
//        ElasticsearchConfig.print(response);
//
//        UpdateResponse responseScript = client.prepareUpdate("twitter", "tweet", "1")
//                .setScript(new Script("ctx._source.user = \"adnsa\""))
//                .get();
//        ElasticsearchConfig.print(responseScript);
//        UpdateResponse responseBuilder = client.prepareUpdate("twitter", "tweet", "1")
//                .setDoc(jsonBuilder()
//                        .startObject()
//                        .field("user", "asdadsaf")
//                        .endObject())
//                .get();
//        ElasticsearchConfig.print(responseBuilder);

        //upsert
        String json = "{" +
                "\"user\":\"kimchy\"," +
                "\"postDate\":\"2013-01-30\"," +
                "\"message\":\"trying out Elasticsearch\"" +
                "}";

        IndexRequest indexRequest = new IndexRequest("index", "type", "1")
                .source(jsonBuilder()
                        .startObject()
                        .field("name", "Joe Smith")
                        .field("gender", "female")
                        .endObject());

        UpdateRequest updateRequestUpsert = new UpdateRequest("index", "type", "4")
                .doc(json, XContentType.JSON)
                .upsert(indexRequest);
        UpdateResponse responseUpsert = client.update(updateRequestUpsert).get();
        ElasticsearchConfig.print(responseUpsert);
    }


}
